from fastapi.responses import ORJSONResponse
from fastapi.routing import APIRouter
from extensions.utils import *
from fastapi.responses import JSONResponse
from concurrent.futures import ThreadPoolExecutor, as_completed
from fastapi import Request

Mongo = MongoConn(log=False, db='KafkaPro')
fs = GridFS(Mongo.db)

router = APIRouter(
    prefix="/api",
    tags=["redis"],
    default_response_class=ORJSONResponse
)
bootstrap_servers = '172.19.1.209:9092'
topic = 'finance_tax_task_status_demo'


@router.post("/redis/list")
async def reids_List(item: dict):
    # Kafka集群的连接信息
    try:
        query_data = Mongo.findall('redis', {"RedisHost": item.get('host')})[0]
        query = {
            "host": item.get('host') or "localhost",
            "port": item.get('port') or 6379,
            "password": item.get('password'),
            "db": query_data.get('db') or 0,
        }
        path = item.get('path')
        data = RedisApi(**query).get_keys(path)
        return JSONResponse(status_code=200, content={"data": data, "status": "success", "msg": "获取redis成功"})
    except Exception as e:
        logger.info(e)
        return JSONResponse(status_code=200, content={"data": [], "status": False, "msg": "连接失败"})


@router.post("/redis/db")
async def reids_DB(item: dict):
    # Kafka集群的连接信息
    try:
        f = {"RedisHost": item.get('host')}
        query_data = Mongo.findall('redis', {"RedisHost": item.get('host')})[0]
        query_data['db'] = item.get('db')
        Mongo.update_many('redis', filter=f, data=query_data)
        return JSONResponse(status_code=200, content={"status": "success", "msg": "redis db修改成功"})
    except Exception as e:
        logger.info(e)
        return JSONResponse(status_code=200, content={"status": False, "msg": "redis db修改失败"})


@router.post("/redis/get/db")
async def reids_GetDB(item: dict):
    # Kafka集群的连接信息
    try:
        query_data = Mongo.findall('redis', {"RedisHost": item.get('host')})
        query_data = foomatMid(query_data)[0]
        return JSONResponse(status_code=200, content={"data": query_data, "status": "success", "msg": "redis db获取成功"})
    except Exception as e:
        logger.info(e)
        return JSONResponse(status_code=200, content={"data": None, "status": False, "msg": "redis db获取失败"})


@router.post("/reids/data")
async def reids_data(item: dict):
    data = Mongo.findall('redis', )
    json_data = foomatMid(data)
    return JSONResponse(status_code=200, content={"data": json_data, "status": "success", "msg": "获取redis成功"})


@router.post("/redis/add")
async def redis_add(item: dict):
    dt = datetime.datetime.now()
    Name = item.get('Name')
    RedisHost = item.get('RedisHost', 'localhost')
    Port = item.get('Port', 6379)
    query = {
        "Name": Name,
    }
    if Mongo.find_query('redis', query):
        return JSONResponse(status_code=200, content={"status": False, "msg": "Redis连接名已存在"})
    else:
        item.update({"Port": Port, "RedisHost": RedisHost})
        query.update(**item)
        query.update({"datetime": str(dt)})
        Mongo.insert('redis', query)
        return JSONResponse(status_code=200, content={"status": True, "msg": "创建成功"})


@router.post("/redis/edit")
async def Consumer_edit(item: dict):
    dt = datetime.datetime.now()
    try:
        item = item.get('old')
        id = item.get('_id')
        item_dict = {
            '_id': ObjectId(id),
        }
        new = item
        new['_id'] = ObjectId(id)
        new.update({"updatetime": str(dt)})
        Mongo.update_many('redis', filter=item_dict,
                          data=new)
        return JSONResponse(status_code=200, content={"status": True, "msg": "修改成功"})
    except Exception as e:
        return JSONResponse(status_code=200, content={"status": False, "msg": "修改失败"})


@router.post("/redis/test")
async def redis_test(item: dict):
    host = item.get('RedisHost') or 'localhost'
    port = item.get('Port') or 6379
    password = item.get('Password')
    item_dict = {
        'host': host,
        'port': port,
        'password': password,
        'db': 0,
    }
    test_code = RedisApi(**item_dict).ok
    print(item_dict, test_code)
    if test_code:
        return JSONResponse(status_code=200, content={"status": True, "msg": "测试连接成功"})
    else:
        return JSONResponse(status_code=200, content={"status": False, "msg": "测试连接失败"})


@router.post("/redis/del")
async def Consumer_del(item: dict):
    get_id = item.get('_id')
    query = {
        "_id": ObjectId(get_id),
    }
    try:
        Mongo.delete_query('redis', query)
        return JSONResponse(status_code=200, content={"status": True, "msg": "删除成功"})
    except Exception as e:
        print(e)
        return JSONResponse(status_code=200, content={"status": False, "msg": "删除失败"})


@router.post("/redis/get/data")
async def redis_get_data(request: Request, item: dict):
    query = []
    Name = item.get('Name')
    redis_conf = {
        "host": item.get('host') or 'localhost',
        "port": item.get('port') or 6379,
        "password": item.get('password'),
        "db": item.get('db') or 0,
    }
    get_type = item.get('type')
    redis_conn = RedisApi(**redis_conf)
    if get_type == 'zset':
        data = redis_conn.get_zset(key=Name)
    elif get_type == 'string':
        data = redis_conn.get_string(key=Name)
    else:
        data = []
    query = data
    return JSONResponse(status_code=200, content={"status": True, "msg": "redis数据获取成功", "data": query})


@router.post("/logs")
async def logs_list(request: Request, item: dict):
    page = item.get('page')
    LogName = item.get('LogName')
    redis_conf = {
        "host": item.get('host') or 'localhost',
        "port": item.get('port') or 6379,
        "password": item.get('password'),
        "db": item.get('db') or 0,
    }
    redis_conn = RedisApi(**redis_conf)
    log = redis_conn.get_redis_list(page=page, LogName=LogName)
    item = {
        'page': page,
        "log": log
    }
    return JSONResponse(status_code=200, content={"status": True, "msg": "log 获取成功", "data": item})


@router.post("/logs/search")
async def logs_list(request: Request, item: dict):
    page = item.get('page')
    search = item.get('search')
    LogName = item.get('LogName')
    redis_conf = {
        "host": item.get('host') or 'localhost',
        "port": item.get('port') or 6379,
        "password": item.get('password'),
        "db": item.get('db') or 0,
    }
    redis_conn = RedisApi(**redis_conf)
    log = redis_conn.get_redis_search_range(
        LogName=LogName, search_keyword=search, all=False)
    item = {
        'page': page,
        "log": log
    }
    return JSONResponse(status_code=200, content={"status": True, "msg": "log 获取成功", "data": item})
